package com.crawler.actor

import akka.actor.{Actor, ActorLogging, Props}
import akka.cluster.routing.{ClusterRouterPool, ClusterRouterPoolSettings}
import akka.routing.RandomPool
import com.crawler.message.TaskParamListMessage
import com.crawler.tables.Tables.TaskRow

/**
  * Created by tongtao.zhu on 2016/11/28.
  */
class RouterActor extends Actor with ActorLogging {
  val taskCollectionRef = context.actorOf(Props[CollectionActor], name = "collectionActor")

  override def postStop(): Unit = {
    log.info("结束一个routerActor")
  }

  override def preStart(): Unit = {
    // 订阅集群事件
    log.info("开始一个routerActor")
  }


  override def receive = {
    case task: TaskRow => {
      workerRouter ! task
    }
    case TaskParamListMessage(tasks) => {
      log.info(workerRouter.path.toStringWithoutAddress)
      workerRouter ! TaskParamListMessage(tasks)

    }
  }

  private val workerRouter = {
    context.actorOf(ClusterRouterPool(
      RandomPool(5),
      ClusterRouterPoolSettings(
        totalInstances = 30,
        maxInstancesPerNode = 6,//启动work节点中actor的数量，启动四个actor节点，因为浏览器的开销很大
        allowLocalRoutees = true,
        useRole = None //可以指定master是否爬取任务 none为爬取，Some("work")指定work爬取任务
      )).props(Props(classOf[CrawlerActor], taskCollectionRef)), name = "worker-router")
  }
}
